import dayjs from 'dayjs';

type TargetContext = '_self' | '_parent' | '_blank' | '_top';

export const openWindow = (
  url: string,
  opts?: { target?: TargetContext; [key: string]: any }
) => {
  const { target = '_blank', ...others } = opts || {};
  window.open(
    url,
    target,
    Object.entries(others)
      .reduce((preValue: string[], curValue) => {
        const [key, value] = curValue;
        return [...preValue, `${key}=${value}`];
      }, [])
      .join(',')
  );
};

export const regexUrl = new RegExp(
  '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$',
  'i'
);

// 根据 value 获取 对应 label
export const getLabel = (
  value: any,
  list: any[],
  labelKey = 'label',
  valueKey = 'value'
) => {
  if (!list) return '';
  const obj = list.find((t) => `${t[valueKey]}` === `${value}`);
  if (obj) return obj[labelKey];
  return value;
};

// 深度合并
export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  Object.keys(target).forEach((key) => {
    src[key] =
      Object.prototype.toString.call(src[key]) === '[object Object]'
        ? deepMerge(src[key], target[key])
        : (src[key] = target[key]);
  });
  return src;
}

export function downloadFile(blob: any, fileName: string) {
  const nBlob = new Blob([blob]);
  const url = window.URL.createObjectURL(nBlob);
  const $link = document.createElement('a');
  $link.setAttribute('href', url);
  $link.setAttribute('download', `${fileName}`);
  document.body.appendChild($link);
  $link.click();
}

export const creatDownloadUrl = (
  res: any,
  fileName: string,
  wholeName: boolean,
  type = 'blob'
) => {
  if (type === 'link') {
    const downloadElement = document.createElement('a');
    downloadElement.href = res;
    if (wholeName) {
      downloadElement.download = `${fileName}.xls`;
    } else {
      downloadElement.download = `${fileName}_${dayjs(new Date()).format(
        'YYYY/MM/DD'
      )}.xls`; // 下载后文件名
    }
    document.body.appendChild(downloadElement);
    downloadElement.click(); // 点击下载

    document.body.removeChild(downloadElement); // 下载完成移除元素
    return;
  }
  const blob = new Blob([res], {
    type:
      'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8',
  });

  const nav = window.navigator as any;
  if (nav.msSaveBlob) {
    // 没有此判断的话，ie11下的导出没有效果
    nav.msSaveBlob(blob, unescape(res.headers.filename.replace(/\\u/g, '%u')));
  } else {
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(blob); // 创建下载的链接
    downloadElement.href = href;
    if (wholeName) {
      downloadElement.download = `${fileName}.xls`;
    } else {
      downloadElement.download = `${fileName}_${dayjs(new Date()).format(
        'YYYY/MM/DD'
      )}.xls`; // 下载后文件名
    }
    document.body.appendChild(downloadElement);
    downloadElement.click(); // 点击下载

    document.body.removeChild(downloadElement); // 下载完成移除元素
    window.URL.revokeObjectURL(href); // 释放掉blob对象
  }
};

export const getUrl = () => {
  const url = window.location.href;
  const search = url.slice(0, url.indexOf('?'));
  return search;
};

export const getLocationObj = () => {
  const url = window.location.href;
  const search = url.slice(url.indexOf('?'));
  const params = new URLSearchParams(search);
  return params;
};

export const getLocationSearch = (key: string) => {
  const params = getLocationObj();
  return params.get(key);
};

export const delLocationSearch = (keys: string[]) => {
  const params = getLocationObj();
  keys.forEach((t) => {
    params.delete(t);
  });
  return params.toString();
};
